package top.ezzz.tool;

import cn.hutool.core.date.DateTime;
import lombok.extern.slf4j.Slf4j;
import org.noear.solon.scheduling.annotation.Scheduled;
import top.ezzz.model.ProcessInfo;
import top.ezzz.util.ProcessUtil;

import java.util.List;
import java.util.concurrent.ConcurrentHashMap;
import java.util.concurrent.ConcurrentMap;

@Slf4j
public class ProcessTask {
    
    // 进程数据缓存
    private static final ConcurrentMap<String, List<ProcessInfo>> processCache = new ConcurrentHashMap<>();
    private static final ConcurrentMap<String, Long> cacheTimestamp = new ConcurrentHashMap<>();
    
    // 缓存过期时间（毫秒）
    private static final long CACHE_EXPIRE_TIME = 30 * 1000; // 30秒
    
    @Scheduled(fixedRate = 10 * 1000) // 每10秒执行一次
    public void cacheProcessData() {
        try {
            log.info("开始缓存进程数据 - " + new DateTime(System.currentTimeMillis()));
            
            // 缓存各种类型的进程数据
            cacheProcessType("java", ProcessUtil.getProcessesByType("java"));
            cacheProcessType("python", ProcessUtil.getProcessesByType("python"));
            cacheProcessType("cpp", ProcessUtil.getProcessesByType("cpp"));
            cacheProcessType("port", ProcessUtil.getProcessesByType("port"));
            cacheProcessType("all", ProcessUtil.getAllProcesses());
            
            log.info("进程数据缓存完成，共缓存 {} 种类型", processCache.size());
            
        } catch (Exception e) {
            log.error("缓存进程数据失败", e);
        }
    }
    
    private void cacheProcessType(String type, List<ProcessInfo> processes) {
        processCache.put(type, processes);
        cacheTimestamp.put(type, System.currentTimeMillis());
    }
    
    /**
     * 获取缓存的进程数据
     */
    public static List<ProcessInfo> getCachedProcesses(String type) {
        if (isCacheValid(type)) {
            return processCache.get(type);
        }
        return null;
    }
    
    /**
     * 检查缓存是否有效
     */
    private static boolean isCacheValid(String type) {
        Long timestamp = cacheTimestamp.get(type);
        if (timestamp == null) {
            return false;
        }
        return (System.currentTimeMillis() - timestamp) < CACHE_EXPIRE_TIME;
    }
    
    /**
     * 获取所有缓存类型
     */
    public static List<String> getCachedTypes() {
        return processCache.keySet().stream().toList();
    }
    
    /**
     * 清除过期缓存
     */
    @Scheduled(fixedRate = 60 * 1000) // 每分钟清理一次过期缓存
    public void cleanExpiredCache() {
        long currentTime = System.currentTimeMillis();
        cacheTimestamp.entrySet().removeIf(entry -> 
            (currentTime - entry.getValue()) > CACHE_EXPIRE_TIME);
        
        processCache.entrySet().removeIf(entry -> 
            !cacheTimestamp.containsKey(entry.getKey()));
    }
}